# -*- coding: utf-8 -*-
from django.test import TestCase
from django.conf import settings

class GaeCacheTest(TestCase):
    def test_stats_interface(self):        
        from django_gae_cache.api import Api
        
        a = Api()
        ret = a.Stats()
        #print ret
        
        self.failUnless(ret[0] == 0, "Return code 0 expected")
        self.failUnless(ret[1] == u'OK', "Return message 'OK' expected")
        self.failUnless(len(ret[2]) == 6, "Data dictionary with 6 keys expected")

    def test_cache_resource(self):
        import os
        import urllib
        import sys
        from django_gae_cache.api import Api
        
        a = Api()
        
        teststring = "This is content of testing file"
        testname = 'gaecache_test.txt'
        test_file = os.path.join(settings.MEDIA_ROOT, testname)
        test_url = ''.join([settings.MEDIA_URL, testname])

        # Delete file (for sure)
        try:
            os.unlink(test_file)
        except:
            pass
        
        # Delete cache (for sure)
        a.Invalidate(test_url)
       
        # Try to download. Should return 404 Not Found
        url = urllib.urlopen(''.join([settings.GAE_CACHE_URL, test_url]))
        if sys.version_info >= (2, 6):
            self.failUnless(url.getcode() == 404, "Resource shouldn't exists, expected 404 Not Found")
        data = url.read(len(teststring))
        self.failUnless(data != teststring, "Resource shouldn't exists, expected different (or blank) content")
        url.close()
        
        # Delete cache again, for case when GAE app have '404' in config.STATUS_STORE
        a.Invalidate(test_url)
        
        # Create resource with some simple content
        f = file(test_file, 'w')
        f.write(teststring)
        f.close()
       
        # Try to download again. Now we should get correct file
        url = urllib.urlopen(''.join([settings.GAE_CACHE_URL, test_url]))
        data = url.read(len(teststring))
        if sys.version_info >= (2, 6):
            self.failUnless(url.getcode() == 200, "Resource should exists, expected 200 OK")
        self.failUnless(data == teststring, "Content of testing file differs from original source")
        url.close() 
   
        # Try to download once more, to test loading resource from cache
        url = urllib.urlopen(''.join([settings.GAE_CACHE_URL, test_url]))
        data = url.read(len(teststring))
        if sys.version_info >= (2, 6):
            self.failUnless(url.getcode() == 200, "Resource should be loaded from GAE cache, expected 200 OK")
        self.failUnless(data == teststring, "Content of cached testing file differs from original source")
        url.close()
        
        # Last invalidate of cache, GAE should always return (0, 'OK')
        self.failUnless(a.Invalidate(test_url) == (0, u'OK'), "Cache file should be deleted now")
        
        # Delete testing file from resource
        os.unlink(test_file)
